package com.hr.error;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author DSL
 * @create 2024-10-23 11:11
 */
@RestControllerAdvice//是@ControllerAdvice和@ResponseBody的组合注解
@RequestMapping//统一返回json格式
//@ResponseBody//直接返回字符串给前端，不要找视图解析器！！！
public class GlobalExceptionHandler {//全局异常处理器
//    处理自定义异常
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<ErrorResponse> handleCustomException(CustomException e) {
        ErrorResponse errorResponse = new ErrorResponse(e.getCode(), e.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(ArithmeticException.class)//捕获算术异常
    public  ResponseEntity<ErrorResponse> ArithmeticException(ArithmeticException e) {
        String message = e.getMessage();
        ErrorResponse errorResponse = new ErrorResponse(4001, message);
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }
//    全局异常 空指针异常
    @ExceptionHandler(NullPointerException.class)//捕获空指针异常
       public  ResponseEntity<ErrorResponse> NullPointerException(NullPointerException e) {
           String message = e.getMessage();
            ErrorResponse errorResponse = new ErrorResponse(4003, message);
           return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }
    //    全局异常
    @ExceptionHandler(Exception.class)//捕获所有异常
    public  ResponseEntity<ErrorResponse> Exception(Exception e) {
        String message = e.getMessage();
        // 根据异常类型或消息决定返回的状态码
        HttpStatus status=HttpStatus.INTERNAL_SERVER_ERROR;
        if (e instanceof IllegalArgumentException) {
            status = HttpStatus.BAD_REQUEST;
        } else if (e instanceof NullPointerException) {
            status = HttpStatus.BAD_REQUEST;
        } else if (e instanceof ArithmeticException) {
            status = HttpStatus.BAD_REQUEST;
        } else if (e.getMessage() != null && e.getMessage().contains("特定错误消息")) {
            status = HttpStatus.NOT_FOUND;
        }
        ErrorResponse errorResponse = new ErrorResponse(4002, e.getMessage());
        return new ResponseEntity<>(errorResponse, status);
    }

}
